package com.wocao.utils.log;

import com.wocao.entity.SysLogininfor;
import com.wocao.service.SysLogininforService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


/**
 * 日志通知类
 */
// 1. 配置增强  被扫描到自动加到容器中去
@Aspect
// 1. 交给IOC管理
@Component
@EnableAspectJAutoProxy
public class LoginLogAdvise {

    @Autowired
    private SysLogininforService sysLogininforService;

    // 2.
    // 定义切点
    @Pointcut("execution(* com.wocao.config.LoginSuccessHandler.onAuthenticationSuccess()) || @annotation(com.wocao.utils.log.LoginLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = null;
        SysLogininfor login = new SysLogininfor();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        /*获取所有前置需要的值*/
        // 获取当前的用户名
        // ip地址————地址描述
        String meId = request.getRemoteAddr();
        login.setIpaddr(meId);
        if (meId.equals("127.0.0.1")) {
            login.setLoginLocation("内网IP");
        } else {
            login.setLoginLocation("XX XX");
        }
        // 浏览器类型
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        Browser browser = userAgent.getBrowser();
        login.setBrowser(browser.getName() + "-" + browser.getVersion(header));
        // 操作系统
        OperatingSystem os = userAgent.getOperatingSystem();
        login.setOs(os.getName());
        // 登录状态
        login.setStatus("0");
        // 提示信息
        login.setMsg("登录成功");
        // 访问时间
        login.setLoginTime(LocalDateTime.now());

        /*执行原有方法*/
        try {
            proceed = joinPoint.proceed();
            /*执行后期通知*/

            return proceed;
        } catch (Exception e) {
            /*获取异常信息*/
            // 登录状态
            login.setStatus("1");
            // 提示信息
            login.setMsg(e.getMessage());
        }
        sysLogininforService.save(login);
        return proceed;
    }
}
